package org.qiandaosystem.qiandaosystemsource.controller;

import org.qiandaosystem.qiandaosystemsource.dto.ExportSignStatusDto;
import org.qiandaosystem.qiandaosystemsource.service.SignRecordService;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import java.util.List;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
public class SignRecordController {

    @Autowired
    private SignRecordService signRecordService;

    @PostMapping(value = "/exportSignStatus")
    public ResponseEntity<byte[]> exportSignStatus(@RequestParam("activityId") Integer activityId,
                                                   @RequestParam("fileName") String fileName) {
        List<ExportSignStatusDto> exportDtos = signRecordService.getSignStatusByActivityId(activityId);

        // 构建导出参数
        ExportParams exportParams = new ExportParams("签到情况", "签到表", ExcelType.XSSF);

        // 导出 Excel
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ExportSignStatusDto.class, exportDtos);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fileName + ".xlsx");

        // 将工作簿写入响应体
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            workbook.write(outputStream);
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(outputStream.size())
                    .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
                    .body(outputStream.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}